package com.cdgeekcamp.redas.recr_page_worker.component;

import com.cdgeekcamp.redas.db.model.PositionTag;
import com.cdgeekcamp.redas.db.model.PositionTagRepository;
import com.cdgeekcamp.redas.db.model.R_PositionTag;
import com.cdgeekcamp.redas.db.model.R_PositionTagRepository;
import com.cdgeekcamp.redas.lib.core.api.receivedParameter.RecrPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Optional;

@Component
public class PositionTagBuildServiceImpl implements RecrPageBuildService {
    @Autowired
    private PositionTagRepository positionTags;

    @Autowired
    private R_PositionTagRepository r_positionTags;

    public Integer build(RecrPage recrPage, Integer... relatedIds) {
        ArrayList<String> tagList = recrPage.getTagList();

        for (String tag : tagList) {
            Optional<PositionTag> positionTagOpt = positionTags.findByTag(tag);
            PositionTag positionTag;

            if (positionTagOpt.isEmpty()) {
                positionTag = positionTags.save(new PositionTag(tag));
                log.info(String.format("职位标签：%s 不存在，新建中......", tag));
            } else
                positionTag = positionTagOpt.get();

            Integer positionId = relatedIds[0];
            Integer tagId = positionTag.getId();

            Optional<R_PositionTag> r_positionTagOpt = r_positionTags.findByTagIdAndPositionId(tagId, positionId);

            if (r_positionTagOpt.isEmpty()) {
                r_positionTags.save(new R_PositionTag(tagId, positionId));
                log.info(String.format("标签：%s->公司：%s关联不存在，新建中......", tagId, positionId));
            } else
                log.info(String.format("标签：%s->公司：%s关联已经存在......", tagId, positionId));
        }

        return 0;
    }
}
